<template>
  <tm-app
    :transparent="true"
    :style="{
      overflow: 'hidden'
    }"
  >
    <view class="custom-login">
      <view class="custom-login-top">
        <img
          class="custom-login-top-logo"
          src="../../static/tabbar-ico/logo.png"
        />
        <view class="custom-login-top-title">浙里资产</view>
      </view>
      <view class="custom-login-tabs">
        <tm-tabs
          @change="tabItem => (currentTabs = tabItem)"
          showTabsLineAni
          :transprent="true"
          :list="LoginTabs"
          :item-width="180"
          :activeFontColor="'#366EF4'"
          :width="636"
          default-name="1"
        ></tm-tabs>
      </view>
      <view class="custom-login-input">
        <!-- 账号密码登录 -->
        <template v-if="currentTabs === 'pwd'">
          <tm-input
            :border="2"
            :height="96"
            v-model="loginParams.account"
            showClear
            placeholder="请输入账号"
            :margin="[0, 32]"
            class="zhanghao"
            errorLabel="账号不能为空"
          >
            <template #left>
              <img
                src="../../static/login/person.svg"
                alt=""
                class="custom-use-svg"
              />
            </template>
          </tm-input>
          <tm-input
            v-model="loginParams.password"
            :border="2"
            :height="96"
            password
            placeholder="请输入密码"
            :margin="[0, 32]"
          >
            <template #left>
              <img
                src="../../static/login/pwd.svg"
                alt=""
                class="custom-use-svg"
              />
            </template>
          </tm-input>
          <tm-input
            :border="2"
            :height="96"
            v-model="loginParams.dynamicCode"
            showClear
            placeholder="请输入验证码"
          >
            <template #left>
              <img
                src="../../static/login/pwd.svg"
                alt=""
                class="custom-use-svg"
              />
            </template>
            <template #right>
              <tm-button
                @click="getDynamicCode"
                transprent
                text
                :shadow="0"
                size="normal"
                :label="buttonText"
                :disabled="countdown > 0"
              ></tm-button>
            </template>
          </tm-input>
        </template>
        <!-- 短信验证登录 -->
        <template v-else>
          <tm-input
            :border="2"
            :height="96"
            v-model="loginParams.account"
            showClear
            placeholder="请输入手机号"
            :margin="[0, 32]"
          >
            <template #left>
              <img
                src="../../static/login/phone.svg"
                alt=""
                class="custom-use-svg"
              />
            </template>
          </tm-input>
          <tm-input
            :border="2"
            :height="96"
            v-model="loginParams.dynamicCode"
            showClear
            placeholder="请输入验证码"
          >
            <template #left>
              <img
                src="../../static/login/pwd.svg"
                alt=""
                class="custom-use-svg"
              />
            </template>
            <template #right>
              <tm-button
                transprent
                text
                :shadow="0"
                size="normal"
                label="发送验证码"
              ></tm-button>
            </template>
          </tm-input>
        </template>
      </view>
      <view class="custom-login-button">
        <tm-button
          color="#366EF4"
          fontColor="#fff"
          block
          label="登录"
          @click="login"
        ></tm-button>
      </view>
    </view>
  </tm-app>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import OrgCtrl from '../../ts/controller'
import type { LoginParamsType, LoginType } from './config'
import { LoginTabs } from './config'
import { onLoad, onShow } from '@dcloudio/uni-app'
// #ifdef H5
import zzd from 'gdt-jsapi'
// #endif
const countdown = ref(0)
const countdownInterval = ref(null)
const buttonText = ref('发送验证码')
/**  默认账号密码登录 */
const currentTabs = ref<LoginType>('pwd') //
/**  账号密码/短信验证码登录 */
const loginParams = reactive<LoginParamsType>({
  account: '',
  password: '',
  dynamicId: '',
  dynamicCode: ''
})

onLoad(option => {
  if (option?.clear === '1') {
    // #ifndef H5
    uni.removeStorageSync('accessToken')
    // #endif

    // #ifdef H5
    sessionStorage.removeItem('accessToken')
    // #endif
  }
})

onShow(() => {
  /** 账号密码存储功能 */
  const loginPar = uni.getStorageSync('LoginParams')
  if (loginPar) {
    const val = JSON.parse(loginPar)
    loginParams.account = val.account
    loginParams.password = val.pwd
  }
})

/** 提交参数校验 */
function validate(loginType: LoginType): boolean {
  switch (loginType) {
    case 'pwd':
      if (loginParams.account === '' || loginParams.password === '') {
        uni.showToast({
          title: '请输入信息',
          icon: 'none'
        })
        return false
      }
      if (!/(\d{6})/.test(loginParams.dynamicCode ?? '')) {
        uni.showToast({
          title: '请输入正确的验证码',
          icon: 'none'
        })
        return false
      }
      break
    case 'dynamicCode':
      loginParams.password = ''

      if (!uni.$tm.u.isPhone(loginParams.account)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return false
      }
      if (!/(\d{6})/.test(loginParams.dynamicCode ?? '')) {
        uni.showToast({
          title: '请输入正确的验证码',
          icon: 'none'
        })
        return false
      }
      break
    default:
      console.error('暂不支持该登录方式：' + loginType)
      break
  }
  return true
}

/** 登录 */
async function login() {
  if (validate(currentTabs.value)) {
    const res = await OrgCtrl.auth.login(loginParams)
    if (res.code === 200) {
      uni.showToast({
        title: '登录成功',
        icon: 'none'
      })
      uni.setStorageSync('isClear', true)
      // #ifdef H5 || MP-ALIPAY
      zzd.getAuthCode({}).then(result => {
        // zzd.alert({
        //   message: JSON.stringify(res.data.accessToken)
        // })
        if (result) {
          uni.request({
            url: 'http://zydd.orginone.org.cn/ZZDLogin.bind',
            method: 'POST',
            header: {
              'Content-Type': 'application/json'
            },
            data: {
              accessToken: res.data.accessToken,
              decryptData: result.code || ''
            },
            success: _res => {
              // zzd.alert({
              //   message: JSON.stringify(res.data)
              // })
            },
            fail: _err => {}
          })
        }
      })
      // #endif
      uni.reLaunch({
        url: '/pages/home/home'
      })
      uni.setStorageSync(
        'LoginParams',
        JSON.stringify({
          account: loginParams.account,
          pwd: loginParams.password
        })
      )
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'error'
      })
    }
  }
}
const getDynamicCode = async () => {
  if (loginParams && loginParams.account.length > 0 && loginParams.password) {
    const res = await OrgCtrl.auth.dynamicCode({
      account: loginParams.account,
      platName: '预算管理一体化',
      dynamicId: ''
    })
    if (res.success && res.data) {
      //发送成功，倒计时
      startCountdown()
      loginParams.dynamicId = res.data.dynamicId
    }
  }
}
const startCountdown = () => {
  countdown.value = 60
  buttonText.value = `${countdown.value}秒后重新发送`
  countdownInterval.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
      buttonText.value = `${countdown.value}秒后重新发送`
    } else {
      clearInterval(countdownInterval.value)
      buttonText.value = '再次发送'
    }
  }, 1000)
}
</script>

<style lang="scss" scoped>
.custom-login {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(#bbdefc, 10%, #fff);
  background-size: 100% 100%;
  box-sizing: border-box;
  padding-left: 32rpx;
  padding-right: 32rpx;
  .custom-login-top {
    margin-top: 30%;
    margin-bottom: 150rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .custom-login-top-logo {
      width: 82rpx;
      height: 82rpx;
    }
    .custom-login-top-title {
      font-size: 52rpx;
      font-weight: 500;
      margin-left: 10rpx;
    }
  }
  .custom-login-tabs {
    width: 100%;
    margin-bottom: 40rpx;
  }
  .custom-login-input {
    width: 100%;
    margin-top: 32rpx;
    margin-bottom: 64rpx;
    .custom-use-svg {
      width: 40rpx;
      height: 40rpx;
      margin-right: 16rpx;
    }
    .zhanghao {
      background-color: red;
    }
  }
  .custom-login-button {
    width: 100%;
    height: 100rpx;
    margin-bottom: 32rpx;
  }
}
</style>
